package com.xiaoluo.web.k8;


import com.xiaoluo.common.utils.JsonUtils;
import com.xiaoluo.service.KubernetesService;
import com.xiaoluo.service.ServerService;
import com.xiaoluo.web.BaseController;
import com.xiaoluo.web.form.ControllerForm;
import com.xiaoluo.web.form.ResultForm;
import io.fabric8.kubernetes.api.model.*;
import io.fabric8.kubernetes.client.KubernetesClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;

/**
 * Project : SpiderManager
 * Package : com.xiaoluo.web
 * Created by Willian.
 * Date  : 2015/10/21 20:29.
 */
@Controller
@RequestMapping("/replication")
public class ReplicaController extends BaseController {
    private final static Logger logger = LoggerFactory.getLogger(ReplicaController.class);

    @Autowired
    private ServerService serverService;
    @Autowired
    private KubernetesService kubernetesService;


    @RequestMapping(value = "/")
    public  String index(ModelMap model,String type){

        PodList pods = kubernetesService.getClient().pods().list();
        model.addAttribute("pods",pods);
        model.addAttribute("type",type);
        return "k8/controllers";
    }

    @RequestMapping(value = "/viewReplication",method = RequestMethod.GET)
    public  String viewReplication(ModelMap model,String namespace,String name){

        if(name !=null && !"".equals(name)){
            ReplicationController controller = kubernetesService.getClient().replicationControllers().inNamespace(namespace).withName(name).get();
            model.addAttribute("controller",controller);
        }

        model.addAttribute("nodes",kubernetesService.getClient().nodes().list());
        model.addAttribute("namespaces",kubernetesService.getClient().namespaces().list());
        return "k8/replicationController/detail";
    }

    @RequestMapping(value = "/del")
    public  String del(ModelMap model,String namespace,String name){

        logger.info("User:{},Del replicationController:{}",getCurrentUser().getUserName(),name);

        if(name !=null && !"".equals(name)){
            kubernetesService.getClient().replicationControllers().inNamespace(namespace).withName(name).delete();
        }

        return "forward:/replication/";
    }
    @RequestMapping(value = "/save",produces = "application/json; charset=UTF-8")
    @ResponseBody
    public ResultForm save(ModelMap model,@RequestBody String params){
        logger.info("User:{},save replicationController:{}",getCurrentUser().getUserName(),params);
        ResultForm result = new ResultForm(0,"success");

        try {
            ControllerForm form = JsonUtils.mapper.readValue(params, ControllerForm.class);

            if(form.getOldName() != null && !"".equals(form.getName()))
                if (form.getOldName().equals(form.getName()) && form.getOldNamespace().equals(form.getNamespace())) {
                    //replace
                    DoneableReplicationController controller1 = kubernetesService.getClient().inNamespace(form.getNamespace()).replicationControllers().withName(form.getName()).edit();
                    controller1.editSpec()./*addToSelector(selector).withSelector(form.getSelectorMap()).*/withReplicas(Integer.parseInt(form.getReplicas())).endSpec();
                    controller1.done();
                } else {
                    //update
                    DoneableReplicationController controller = kubernetesService.getClient().inNamespace(form.getOldNamespace())
                            .replicationControllers()
                            .withName(form.getOldName()).edit();

                    controller.editMetadata().withName(form.getName());
                    controller.editMetadata().withNamespace(form.getNamespace());
                    controller.editSpec().withReplicas(Integer.parseInt(form.getReplicas()));

                    if(form.getSelectorMap().size() >0){
                        controller.editSpec().withSelector(form.getSelectorMap());
                    }

                    controller.done();
                }
            else {
                //new
                EditableReplicationController controller = new ReplicationControllerBuilder().withNewMetadata()
                        .withName(form.getName())
                        .withNamespace(form.getNamespace())
                        .withLabels(form.getLabelsMap())
                        .endMetadata()
                        .withNewSpec()
                        .withSelector(form.getSelectorMap())
                        .endSpec()
                        .build();


                kubernetesService.getClient().replicationControllers().create(controller);
            }

        } catch (IOException e) {
            e.printStackTrace();
            result.setMsg(e.getMessage());
            result.setCode(-1);
        }

        return result;
    }

}
